<?php
namespace app\interfaces\controller;

use app\interfaces\model\Member as MemberModel;
use app\interfaces\model\MemberBrokerage as MemberBrokerageModel;
use app\interfaces\model\MemberDistribution as MemberDistributionModel;
use app\interfaces\model\MemberDistributionOrder as MemberDistributionOrderModel;
use app\interfaces\model\CashWithdrawal as CashWithdrawalModel;
use think\Request;
use think\Db;
use think\Exception;

class MemberBrokerage
{

    /*
     * 用户端 - 佣金首页
     * @param  string $user_id 会员ID
     */
    public function brokerage_index()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id', '596');

        if (empty($user_id)) throw new Exception('not Empty');

        $model = new MemberBrokerageModel();

        $result = $model->where(['member_id' => $user_id])->field('member_id', true)->find();

        // halt($result);

        // 下级分销商人总数
        $level = MemberDistributionModel::where('referrals_id', $user_id)->value('level');
        // 分销商人总数 (自己下两级)
        $result['distribution'] = MemberDistributionModel::where([
            'hierarchy' => ['like', '%,' . $user_id . ',%'],
            'level'     => ['elt', $level + 2]
        ])->count();


        //查找分销会员id
        $result['distribution_ids'] = MemberDistributionModel::where([
            'hierarchy' => ['like', '%' . $user_id . '%'],
            'level'     => ['elt', ($level + 2)],   //只查下两级
        ])->column('referrals_id');

        $result['distribution_order'] = 0;

        //所有下2级分销商
        $data = (new MemberDistributionModel())
            ->where([
                'sun_member_distribution.level'     => ['elt', ($level + 2)],   //只查下两级
                'sun_member_distribution.hierarchy' => ['like', '%,' . $user_id . ',%']
            ])
            ->with([
                'member',
                'memberDistributionOrder' => function ($e) use ($user_id){
                    $e
                        ->where('distribution_id', $user_id);  //分销订单上级会员id是当前会员
                }
            ])
            ->order(['create_time' => 'desc'])->select();

        $num = 0;
        if ($data) {
            foreach ($data as $key => &$item) {
                if (!$item['member'] || !$item['member_distribution_order']) {
                    unset($data[$key]);
                } else {
                    foreach ($item['member_distribution_order'] as $o) {
                        $o->memberOrder;    //分销订单关联会员已产生佣金的订单[状态为3,4]
                    }
                    foreach ($item['member_distribution_order'] as $_key => $_item) {
                        if (!is_null($_item['memberOrder'])) {
                            $num++;
                        }
                    }
                }
            }
        }

        //分销会员已产生佣金的订单数量 (按店铺计)
        $result['distribution_order_count'] = $num;

        //从分销会员那里收入的佣金
        $distribution_brokerage = (new MemberDistributionOrderModel())
            ->where([
                'sun_member_distribution_order.member_id'       => ['in', implode(',', $result['distribution_ids'])],
                'sun_member_distribution_order.distribution_id' => $user_id,
            ])->with(['memberOrder'])->select();


        $result['distribution_brokerage'] = "0.00";
        $result['distribution_to_yield'] = "0.00";

        if ($distribution_brokerage) {

            foreach ($distribution_brokerage as $value) {

                if ($value->orderBrokerage) {
                    if (in_array($value->orderBrokerage->status, [3, 4])) {  //下级返给本人已收益

                        $result['distribution_brokerage'] = bcadd($result['distribution_brokerage'], $value->brokerage, 2);
                    } else if (in_array($value->orderBrokerage->status, [0, 1, 2])) {  //下级返给本人待收益

                        $result['distribution_to_yield'] = bcadd($result['distribution_to_yield'], $value->brokerage, 2);

                    }
                }
            }
        }

        //本人周周币(自己买的已收益的)
        $result['self_general_income'] = bcsub(bcsub($result['general_income'], $result['to_yield'], 2), $result['distribution_brokerage'], 2);

        //周周币总收入
        $result['total_money'] = bcadd($result['distribution_brokerage'], $result['general_income'], 2);

        //本人待收益合计
        $result['self_to_yield'] = bcsub($result['to_yield'], $result['distribution_to_yield'], 2);

        //待审核合计
        $result['total_to_audit'] = $model->where(
            'member_id', 'in', implode(',', $result['distribution_ids']) . ',' . $user_id
        )
            ->sum('to_audit');
        //本人订单的数量
        $self_data = MemberDistributionModel::where(
            'sun_member_distribution.referrals_id', $user_id
        )
            ->with([
                'member',
                'memberDistributionOrder' => function ($e) use($user_id){
                    $e
                        ->where('distribution_id', $user_id);  //分销订单上级会员id是当前会员
                }
            ])
            ->select();

        //去除没有会员信息和分销订单的数据
        $self_num = 0;
        if ($self_data) {
            foreach ($self_data as $key => &$item) {
                if (!$item->member || !$item['member_distribution_order']) {
                    unset($self_data[$key]);
                } else {
                    foreach ($item['member_distribution_order'] as $o) {
                        $o->memberOrder;    //分销订单关联会员已产生佣金的订单
                    }
                    foreach ($item['member_distribution_order'] as $_key => $_item) {
                        if (!is_null($_item['memberOrder'])&&$_item['brokerage']!=0) {
                            $self_num++;
                        }
                    }
                }
            }
        }
        $result['self_order'] = $self_num;
        $result['distribution_general_income'] = $result['distribution_brokerage'];
        $result['self_distribution_order'] = $result['self_order'];

        // 验证数据
        $pay_pass = MemberModel::where(['id' => $user_id])->value('pay_pass');

        if (!empty($pay_pass)) {
            $result['pay_pass'] = '1';
        } else {
            $result['pay_pass'] = '0';
        }

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 用户端 - 佣金明细
     * @param  string $user_id 会员ID
     */
    public function brokerage_detail()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $type = Request::instance()->param('type');

        if (empty($user_id)) throw new Exception('not Empty');

        $model = new MemberDistributionOrderModel();
        // 分销订单总数
        if ($type == 1) {
            $result = $model->where(['distribution_id' => $user_id,'brokerage'=>['neq',0]])->order(['id' => 'desc'])->paginate(15);
        }else{
            $result = (new CashWithdrawalModel)->where(['member_id'=>$user_id])->paginate(15);
            foreach ($result as &$value) {
                if ($value['type_id'] == 1) {
                    $value['title'] = "佣金提现到余额";
                    $value['brokerage'] = $value['cash'];
                    $value['create_time'] = date('Y-m-d',$value['create_time']);
                }else{

                    $value['title'] = "佣金提现第三方账户";
                    $value['create_time'] = date('Y-m-d',$value['create_time']);
                    $value['brokerage'] = $value['cash'];
                }
            }
        }


        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 用户端 - 提现
     * @param  string $user_id  会员ID
     * @param  string $price    金额
     * @param  string $way      方式
     * @param  string $name     银行名称
     * @param  string $account  账号
     */
    public function withdraw()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $price = Request::instance()->param('price');
        $way = Request::instance()->param('way');
        $account = Request::instance()->param('account');
        $name = Request::instance()->param('name', '');

        if (empty($user_id) || empty($price) || empty($way) || empty($account)) throw new Exception('not Empty');

        // 用户之前余额
        $amount = MemberBrokerageModel::where(['member_id' => $user_id])->value('actual_amount');

        if ($amount < $price) return ['code' => 402, 'message' => '余额不足'];

        // 启动事务
        Db::startTrans();
        try {

            $information = [
                'member_id'    => $user_id,
                'type_id'      => 2,
                'way'          => $way,
                'account'      => $account,
                'status'       => 3,
                'cash'         => $price,
                'create_time'  => time()
            ];

            // 添加成功

            Db::name('cash_withdrawal')->insert($information);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $price);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_audit',$price);


            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }

    }

    /*
     * 用户端 - 提现到余额
     * @param  string $user_id  会员ID
     * @param  string $price    金额
     */
    public function withdraw_balance()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $price = Request::instance()->param('price');

        if (empty($user_id) || empty($price)) throw new Exception('not Empty');

        // 用户之前佣金余额
        $amount = MemberBrokerageModel::where(['member_id' => $user_id])->value('actual_amount');

        // 账号
        $balance = MemberModel::where(['id' => $user_id])->value('balance');

        if ($amount < $price) return ['code' => 402, 'message' => '余额不足'];

        // 启动事务
        Db::startTrans();
        try {

            // 生成订单号
            $order_number = $this->createNumber();

            $information = [
                'member_id'    => $user_id,
                'type_id'      => 1,
                'way'          => '提现到余额',
                'account'      => '余额账户',
                'status'       => 1,
                'cash'         => $price,
                'create_time'  => time()
            ];

            $sisn = [
                'member_id' => $user_id,
                'type_id'   => 2,
                'price'     => $price,
                'way'       => '佣金提现到余额',
                'name'      => '',
                'real_name' => '',
                'account'   => '',
                'balance'   => $balance+$price,
                'status'    => 1,
                'reason'    => '',
                'order_number' => $order_number,
                'create_time' => time(),
            ];

            // 添加成功

            // 添加成功
            Db::name('member_withdraw')->insert($sisn);
            Db::name('cash_withdrawal')->insert($information);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $price);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('general_income', $price);
            Db::name('member')->where(['id' => $user_id])->setInc('balance', $price);

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功', 'order_number' => $order_number];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }

    }

    /*
     * 生成订单号码
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }

}
